package com.hk.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Optional;

/**
 *
 */
@Slf4j
public class IPUtils {

    /**
     * 获取客户端ip
     *
     * @param request HttpServletRequest
     * @return 客户端ip
     */
    public static Optional<String> getClientIp(HttpServletRequest request) {
        String ips = request.getHeader("x-forwarded-for");
        if (!StringUtils.hasText(ips)) {
            ips = request.getHeader("Proxy-Client-IP");
        }
        if (!StringUtils.hasText(ips)) {
            ips = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!StringUtils.hasText(ips)) {
            ips = request.getRemoteAddr();
        }
        return Arrays.stream(ips.split(",")).filter(i -> !"unknown".equalsIgnoreCase(i)).findFirst();
    }


    private static final String[] IP_HEADER_CANDIDATES = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR"
    };

    public static String getServerIp() {
        if (RequestContextHolder.getRequestAttributes() == null) {
            return "0.0.0.0";
        }
        String ip = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        for (String header : IP_HEADER_CANDIDATES) {
            String ipList = request.getHeader(header);
            if (ipList != null && !ipList.isEmpty() && !"unknown".equalsIgnoreCase(ipList)) {
                ip = ipList.split(",")[0];
            }
        }
        if (!StringUtils.hasText(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip))
            ip = "localhost";
        return ip;
    }
}
